<template>
  <div class="main-layout">
    <div class="profile-card">
      <div class="profile-actions">
        <button class="action-btn back-btn" @click="$router.back()">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="24"
            height="24"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
          >
            <line x1="19" y1="12" x2="5" y2="12"></line>
            <polyline points="12 19 5 12 12 5"></polyline>
          </svg>
          返回
        </button>
        <router-link v-if="isCurrentUser" :to="{ name: 'mine' }" class="action-btn edit-btn">
          跳转到我的页面
        </router-link>
        <button
          v-if="!isCurrentUser && user && user.id && user.nickname"
          class="action-btn chat-btn"
          @click="goChat"
        >
          {{
            console.log(
              '[按钮渲染] user:',
              user,
              'user.id:',
              user && user.id,
              'user.nickname:',
              user && user.nickname,
              'isCurrentUser:',
              isCurrentUser,
            )
          }}
          聊一聊
        </button>
      </div>

      <template v-if="loading">
        <div class="loading">加载中...</div>
      </template>
      <template v-else-if="errorMsg">
        <div class="error-msg">{{ errorMsg }}</div>
      </template>
      <template v-else-if="user">
        <div class="profile-header">
          <img class="avatar" :src="getUserAvatar(user.photo, user.id)" alt="头像" />
          <div class="nickname">{{ user.nickname || '未填写' }}</div>
        </div>
        <div class="profile-info">
          <div class="info-item"><span class="label">用户ID：</span>{{ user.id || '未填写' }}</div>
          <div class="info-item"><span class="label">性别：</span>{{ user.sex || '未填写' }}</div>
          <div class="info-item">
            <span class="label">生日：</span>{{ user.birthday || '未填写' }}
          </div>
          <div class="info-item">
            <span class="label">签名：</span>{{ user.signature || '未填写' }}
          </div>
          <div class="info-item">
            <span class="label">城市：</span>{{ user.location || '未填写' }}
          </div>
          <div class="info-item">
            <span class="label">学校：</span>{{ user.school || '未填写' }}
          </div>
          <div class="info-item"><span class="label">爱好：</span>{{ user.hobby || '未填写' }}</div>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watchEffect } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import api from '@/services/api'
import { useAuthStore } from '@/stores/auth'
import { getUserAvatar } from '@/utils/avatar'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

const userId = computed(() => String(route.params.id))
const nickname = computed(() => route.query.nickname)
const user = ref(null)
const loading = ref(true)
const errorMsg = ref('')

const isCurrentUser = computed(() => {
  return (
    authStore.user &&
    authStore.user.id &&
    userId.value &&
    String(authStore.user.id) === String(userId.value)
  )
})

watchEffect(() => {
  console.log('authStore.user:', authStore.user)
  console.log('userId.value:', userId.value)
  console.log('isCurrentUser:', isCurrentUser.value)
})

async function fetchUser() {
  if (!userId.value) {
    errorMsg.value = '未指定用户ID'
    loading.value = false
    return
  }
  loading.value = true
  errorMsg.value = ''
  try {
    if (isCurrentUser.value) {
      // 获取自己信息
      const res = await api.getUserInfo()
      if (res.data && res.data.code === 0) {
        user.value = res.data.data
      } else {
        errorMsg.value = res.data?.msg || '获取当前用户信息失败'
      }
    } else {
      // 获取他人信息，必须有nickname
      if (!nickname.value) {
        errorMsg.value = '缺少用户昵称，无法查询他人信息'
        return
      }
      const res = await api.getOtherInfo(nickname.value)
      if (res.data && res.data.code === 0) {
        user.value = res.data.data
      } else {
        errorMsg.value = res.data?.msg || `获取昵称为 ${nickname.value} 的用户信息失败`
      }
    }
  } catch (err) {
    errorMsg.value = '获取用户信息时发生网络错误'
    console.error('获取用户数据失败:', err)
  } finally {
    loading.value = false
  }
}

function goChat() {
  console.log('[goChat] user.value:', user.value)
  if (user.value && user.value.id && user.value.nickname) {
    const params = {
      name: 'chatRoom',
      params: { userId: user.value.id },
      query: { nickname: user.value.nickname },
    }
    console.log('[goChat] 跳转参数:', params)
    router.push(params)
  } else {
    console.warn('[goChat] 用户信息不完整，无法跳转', user.value)
  }
}

onMounted(fetchUser)
</script>

<style scoped>
.main-layout {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  background: var(--color-bg);
}
.profile-card {
  width: 100%;
  max-width: 1200px;
  margin: 2.5rem auto 0 auto;
  background: var(--color-input-bg);
  border-radius: 0.7rem;
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
  padding: 2.5rem 1.5rem 2.5rem 1.5rem;
  box-sizing: border-box;
  min-height: 300px;
  position: relative;
}
@media (max-width: 700px) {
  .profile-card {
    max-width: 100%;
    padding: 1.5rem 0.5rem 2rem 0.5rem;
  }
}
.profile-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  padding: 0 0.5rem;
}
.action-btn {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.6rem 1.2rem;
  border-radius: 0.5rem;
  border: none;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition:
    background-color 0.2s,
    box-shadow 0.2s;
  text-decoration: none;
}
.back-btn {
  background-color: var(--color-surface);
  color: var(--color-text);
  border: 1px solid var(--color-border);
}
.back-btn:hover {
  background-color: var(--color-surface-hover);
}
.edit-btn {
  background-color: var(--color-primary);
  color: var(--color-button-text);
}
.edit-btn:hover {
  background-color: var(--color-primary-hover);
}
.chat-btn {
  background-color: var(--color-primary);
  color: var(--color-button-text);
  margin-left: 1rem;
}
.chat-btn:hover {
  background-color: var(--color-primary-hover);
}
.profile-header {
  display: flex;
  align-items: center;
  gap: 1.5rem;
  margin-bottom: 2rem;
  padding: 0 0.5rem;
}
.avatar {
  width: 6rem;
  height: 6rem;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid var(--color-primary);
  background: var(--color-surface, var(--color-input-bg));
}
.nickname {
  font-size: 2rem;
  font-weight: 700;
  color: var(--color-primary);
}
.profile-info {
  display: flex;
  flex-direction: column;
  gap: 1.1rem;
  font-size: 1.08rem;
  color: var(--color-text);
  padding: 0 0.5rem;
  margin-top: 1.2rem;
}
.info-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  background: var(--color-surface, var(--color-input-bg));
  border-radius: 0.3rem;
  padding: 0.5rem 0.8rem;
  margin-bottom: 0.2rem;
  box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.04);
}
.info-item .label {
  color: var(--color-text-label);
  font-weight: 500;
  min-width: 4.2em;
}
.loading {
  color: var(--color-primary);
  font-size: 1.2rem;
  text-align: center;
  margin: 2rem 0;
}
.error-msg {
  color: #e74c3c;
  font-size: 1.1rem;
  text-align: center;
  margin: 2rem 0;
}
</style>
